import { Injectable, NestMiddleware } from '@nestjs/common';
import { ApiException } from 'src/exception/api.exception';
import { JWTUtil } from 'src/utils/jwt';

@Injectable()
export class TokenVerifyMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    const token = req.headers["token"];
    if(!token){
      throw new ApiException("headers not found 'token' key")
    }

    try {
     const decode = JWTUtil.verifyToken(token)
     req.currentUser=()=>{
       return (decode as any).uid
     }
    } catch (error) {
      throw new ApiException((error as Error).message);
    }

    next();
  }
}
